package com.hellohoper.script.config.engine.container.file;

import com.hellohoper.assembly.common.utils.util.JsonUtils;
import com.hellohoper.script.config.admin.app.dao.pojo.ScriptConfig;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by hk on 17/8/21.
 */
@Getter
@Setter
public class ScriptFileOptionService {

    private static final String SCRIPT_PATH = "./script/groovy/";

    public void saveScriptFile(String appName, List<ScriptConfig> scriptConfigs) throws IOException {
        String path = SCRIPT_PATH + appName;
        File file = new File(path);
        if (!file.exists()) {
            FileUtils.touch(file);
        }
        FileUtils.writeStringToFile(file, JsonUtils.toJson(scriptConfigs), "UTF8");
    }

    public List<ScriptConfig> loadScriptConfig(String appName) throws IOException {
        String path = SCRIPT_PATH + appName;
        File file = new File(path);
        if (!file.exists()) {
            // 文件不存在
            return null;
        }
        String data = FileUtils.readFileToString(file, "UTF8");
        List<ScriptConfig> scriptConfigs = JsonUtils.toList(data, ScriptConfig.class);
        return scriptConfigs;
    }
}
